//
//  LoginViewController.swift
//  WeiBlog
//
//  Created by apple on 15/10/16.
//  Copyright © 2015年 xiang. All rights reserved.
//

import UIKit
import SVProgressHUD
class LoginViewController: UIViewController {

    ///视图模型
    var userAccountViewModel = UserAccountViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self

        view = webView
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")

    }
    
    
// MARK:    懒加载
    private var webView:UIWebView = {
        let view = UIWebView()
//        print(view)
        //加载登陆界面
        view.loadRequest(NSURLRequest(URL:NetworkManager.sharedManager.oAuthURL!))
//        view.backgroundColor = UIColor.redColor()
                
        return view
        }()
    
}

// MARK:    自动填充账号密码
extension LoginViewController
{
    @objc private func autoFill(){
        //让webView执行js语句
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18255515732'")
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('passwd').value = '734320168'")
        
    }
    
    @objc private func close(){
        
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}


// MARK:    加载授权页面
extension LoginViewController:UIWebViewDelegate
{
    /// 将要加载页面时调用(每次加载都会调用)
    //UIWebViewNavigationType是加载方式
    //返回值:true加载,false不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        要获取token,必须需要code值,相当于一个钥匙,code值是拼接到 url中的
//        NetworkManager.sharedManager.askForOAuthtoken(<#T##code: String##String#>, finished: <#T##NetworkCallBack##NetworkCallBack##(resultData: AnyObject?, error: NSError?) -> ()#>)

//        print(request)
//        打印request获得
//        (字典)
//        { URL: http://www.baidu.com/?code=91d2fe110e448b13a8ec0f7b24855402 }
        
//        获取url
        let url = request.URL!
//        获取主机ip    url.host
//        获取?后面的参数  url.query
//        print(url.host)
//        下面要做的事情就是,因为授权和取消授权的时候都要跳转到百度,但是我们的功能不是要他跳转,而是单纯获得code值,所以我们需要当他需要跳到百度的时候,返回false,并且干自己需要实现的功能(注意只有授权才会返回code值,取消授权时不会返回code值的,所以回调页面URL可以随便选)
        
        if url.host == "www.baidu.com"{
            guard let query = url.query where query.hasPrefix("code=") else{
                
                //进入到这里说明是取消授权
                //直接关闭
                close()
                return false
            }
            
            let code = query.substringFromIndex("code=".endIndex)
                //请求用户信息
            UserAccountViewModel.sharedUserAccountViewModel.askForUserInfo(code, finished: {(isSuccessed) -> () in
                    //无论成功还是失败,跳转之后都要释放控制器
                
                        //登录成功就切换到欢迎界面
                        if isSuccessed{
                            SVProgressHUD.show()
                            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                                NSNotificationCenter.defaultCenter().postNotificationName("WBJumpToNotification", object: "Welcome")
                                SVProgressHUD.dismiss()
                            })
                        }else{
                            
                            self.dismissViewControllerAnimated(true, completion: nil)
                        }
                })
            // MARK:-------使用 dismiss 的注意点
            /**
                dismiss是父控制器来执行的,虽然是写在被modal出来的控制器里面,当dismiss没完成时,就切换控制器,那么富控制器就会被一直占有
            (所以这个地方把通知放在dismiss的完成闭包里面,通知是同步的)
            
            */
            return false
            }
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
        //页面加载完成让按钮可点击
        navigationItem.rightBarButtonItem?.enabled = true
        
        autoFill()
    }
    
}